package com.lfs.feishu.controller;

import com.alibaba.fastjson.JSON;
import com.lfs.feishu.domain.dto.CardContent;
import com.lfs.feishu.domain.dto.TemplateVariables;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.gson.JsonParser;
import com.lark.oapi.Client;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.im.v1.model.*;

import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.lfs.feishu.constant.AppInfo.*;

@AllArgsConstructor
@RestController
@RequestMapping("/feishu/single")
@Slf4j
public class FeishuSingleSendController {
    private static final String CARD_ID = "AAqxj2bKYM8xP";

    private final Configuration freemarkerConfig;


    @GetMapping("/advancedSend")
    public String advancedSend() throws Exception {
        // 构建client
        Client client = Client.newBuilder(APP_ID, APP_SECRET).build();

        CreateMessageReqBody body = CreateMessageReqBody.newBuilder()
                .receiveId(LFS_UNION_ID)
                .uuid(UUID.randomUUID().toString())
                .build();

        // 构建请求
//        this.textRequest(body);
        this.cardRequest_(body);

        // 创建请求对象
        CreateMessageReq req = CreateMessageReq.newBuilder()
                .receiveIdType("union_id")  //用户ID类型。可选包括：open_id、union_id、user_id、email、chat_id
                .createMessageReqBody(body)
                .build();

        // 发起请求
        CreateMessageResp resp = client.im().v1().message().create(req);

        // 处理服务端错误
        if (!resp.success()) {
            System.out.println(String.format("code:%s,msg:%s,reqId:%s, resp:%s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId(), Jsons.createGSON(true, false).toJson(JsonParser.parseString(new String(resp.getRawResponse().getBody(), StandardCharsets.UTF_8)))));
            throw new RuntimeException("单发消息失败");
        }

        // 业务数据处理
        return resp.getData().getMessageId();
    }


    /**
     * 文本请求
     * @param body 请求体
     */
    private void textRequest(CreateMessageReqBody body) {
        body.setMsgType("text");
        body.setContent("{\"text\":\"何意味\"}");
    }

    /**
     * 卡片请求1
     * @param body 请求体
     */
    private void cardRequest(CreateMessageReqBody body) {
        CardContent cardContent = CardContent.builder()
                .type("template")
                .data(CardContent.ContentData.builder()
                        .template_id(CARD_ID)
//                        .template_version_name("1.0.0")
                        .template_variable(TemplateVariables.builder()
                                .title("何意味")
                                .subTitle("何意味！何意味...")
                                .topPic(TemplateVariables.Pic.builder()
                                        .img_key("img_v3_02qi_5e57dca8-64f2-4c2c-8972-0b40d95fcaeg")
                                        .build())
                                .conclusion("何意味？！")
                                .contentList(List.of(TemplateVariables.Content.builder()
                                        .title("姓名")
                                        .content("神秘人")
                                        .build(), TemplateVariables.Content.builder()
                                        .title("身份")
                                        .content("老资历")
                                        .build()))
                                .buttonText("去看看吧")
                                .address(TemplateVariables.Address.builder()
                                        .pc_url("https://www.baidu.com")
                                        .android_url("https://open.feishu.cn/")
                                        .ios_url("https://open.feishu.cn/")
                                        .url("https://zhuanlan.zhihu.com/")
                                        .build())
                                .build())
                        .build())
                .build();

        body.setMsgType("interactive");
        body.setContent(JSON.toJSONString(cardContent));
    }


    /**
     * 卡片请求2
     * @param body 请求体
     */
    private void cardRequest_(CreateMessageReqBody body) throws Exception {
        body.setMsgType("interactive");

        // 模板数据
        Map<String, Object> data = new HashMap<>();
        data.put("title", "何意味");
        data.put("contentList", List.of(
                Map.of("title", "姓名", "content", "神秘人"),
                Map.of("title", "身份", "content", "老资历")
        ));
        data.put("markdown", "# 大的要来了");
        // 动态控制部分
        data.put("topPic", "img_v3_02qi_5e57dca8-64f2-4c2c-8972-0b40d95fcaeg");
        data.put("subtitle", "何意味！何意味...");
        data.put("conclusion", "何意味？！");
        data.put("buttonText", "去看看吧");
        data.put("address", Map.of(
                "pc_url", "https://www.baidu.com",
                "android_url", "https://open.feishu.cn/",
                "ios_url", "https://open.feishu.cn/",
                "default_url", "https://zhuanlan.zhihu.com/"
        ));


        // 加载模板
        Template template = freemarkerConfig.getTemplate("vertical_card_template.ftl");

        // 渲染模板
        StringWriter writer = new StringWriter();
        template.process(data, writer);

        body.setContent(writer.toString());
    }
}
